package com.xinhe.web.weixin;

import com.xinhe.web.common.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
 @Component
 public class WeixinNotifyUtil {
   private static final String CHARSET = "UTF-8";
   @Autowired
   private HttpServletRequest request;

   public Map<String, String> getNotifyData() {
     Map<String, String> data = new HashMap<>();
     try {
       String strXML = StreamUtils.copyToString((InputStream)this.request.getInputStream(), Charset.forName("UTF-8"));
       DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
       DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
       InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
       Document doc = documentBuilder.parse(stream);
       doc.getDocumentElement().normalize();
       NodeList nodeList = doc.getDocumentElement().getChildNodes();
       for (int idx = 0; idx < nodeList.getLength(); idx++) {
         Node node = nodeList.item(idx);
         if (node.getNodeType() == 1) {
           Element element = (Element)node;
           data.put(element.getNodeName(), element.getTextContent());
         }
       }
       try {
         stream.close();
       } catch (Exception ex) {}

     } catch (Exception e) {
       throw new BusinessException(9001,"微信参数错误");
     }
     return data;
   }
 }